import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:personinfo/page/CarResource.dart';
import 'package:personinfo/page/CircleOfFriend.dart';
import 'package:personinfo/page/Home.dart';
import 'package:personinfo/page/Person.dart';
import 'package:personinfo/states/appController.dart';
import 'package:personinfo/widgets/common/IconText.dart';

import './TabData.dart';
import 'CustomFloatingActionButtonLocation.dart';
import 'NoScalingAnimation.dart';
import 'TipsWindown.dart';

class BottomWidget extends StatefulWidget{
  const BottomWidget({super.key});

  @override
  State<StatefulWidget> createState() => _BottomWidget();
}


const listView = [
  TabData(index: 0,icon: Icons.home, title: "首页"),
  TabData(index: 1,icon: Icons.move_up_sharp, title: "车源"),
  TabData(index: 2,icon: Icons.search, title: "寻车"),
  TabData(index: 3,icon: Icons.message_rounded, title: "行情圈",showBadge: true,badgeNum: "1"),
  TabData(index: 4,icon: Icons.people, title: "我的"),
];

class _BottomWidget extends State<BottomWidget>{
  int currentIndex = 0;

  final List<Widget> _page = [
    const Home(),
    const CarResource(),
    const Text("1212"),
    const CircleOfFriend(),
    const Person()
  ];

  onTabChanged(int index){
    if(index ==2) {
      tipsWindown.dialog(context);
      return;
    }
    setState(() {
      currentIndex = index;
    });
  }

  /**
   * 导航栏
   */
  _navigation(){
    List<Widget> list = [];
    for(var i = 0; i< listView.length;i++){
      list.add(
          Flexible( flex:4,fit: FlexFit.loose,
          child: IconText(
                icon: listView[i].icon,
                text: listView[i].title,
                iconColors: currentIndex==i?Colors.orange: Colors.black,
                textColors: currentIndex==i?Colors.orange: Colors.black,
                showBadge: listView[i].showBadge,
                badgeNum: listView[i].badgeNum,
                padding: const EdgeInsets.fromLTRB(10, 1, 10, 1),
                onTap: (){
                  onTabChanged(i);
                },
            ),
          )

      );
    }
    return list;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    AppController app = Get.put(AppController());
    setState(() {
      currentIndex = app.tabIndex;
    });
  }

  @override
  Widget build(BuildContext context) {
    int _rightSwipeCount = 0;
    DateTime? _lastSwipeTime;
    void _exitApp() {
      SystemNavigator.pop();
    }
    void _showExitDialog() {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('提示'),
          content: const Text('确定要退出应用吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _exitApp();
              },
              child: const Text('退出'),
            ),
          ],
        ),
      );
    }


    void handleRightSwipe() {
      final now = DateTime.now();
      // 如果超过 2 秒无操作，重置计数
      if (_lastSwipeTime == null || now.difference(_lastSwipeTime!) > const Duration(seconds: 2)) {
        _rightSwipeCount = 1;
      } else {
        _rightSwipeCount++;
      }
      _lastSwipeTime = now;

      if (_rightSwipeCount >= 2) {
        _showExitDialog();
        _rightSwipeCount = 0; // 重置
      } else {
        // 可选：提示“再滑一次退出”
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('再滑一次退出应用')),
        );
      }
    }




    return GestureDetector(
      onHorizontalDragEnd: (details) {
        // 判断是否为右滑：velocity < 0 表示从左向右滑（手指向右移动）
        if (details.primaryVelocity != null && details.primaryVelocity! < 0) {
          handleRightSwipe();
        }
      },
      child: Container(
          decoration: const BoxDecoration(color:Colors.black ),
          child:Scaffold(
            body: _page[currentIndex],
            floatingActionButton: FloatingActionButton(
              backgroundColor: Colors.white,
              shape: const CircleBorder(),
              onPressed: (){
                tipsWindown.dialog(context);
              },
              child: const Icon(Icons.add),
            ),
            floatingActionButtonAnimator: NoScalingAnimation(),
            floatingActionButtonLocation: CustomFloatingActionButtonLocation(FloatingActionButtonLocation.centerDocked,-4 ,14),
            bottomNavigationBar: BottomAppBar(
              elevation: 1,
              color: const Color.fromRGBO(244, 243, 248, 1),
              shape: const CircularNotchedRectangle(),
              child:
              Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: _navigation(),
              ),
            ),
          )
      ),
    );
  }


}
